<template>
  <div class="video-concat-editor">
    <h3>拼接编辑器</h3>
    <div class="selected-videos-list">
      <div v-for="(video, index) in videos" :key="video.id" class="concat-video-item">
        <span>{{ index + 1 }}. {{ video.fileName }} ({{ formatDuration(video.duration) }})</span>
        <button @click="removeVideo(index)" class="remove-btn">×</button>
      </div>
    </div>
    <div class="filename-input">
      <el-input
          v-model="outputFilename"
          placeholder="请输入输出文件名（不含扩展名）"
          clearable
      />
      <span class="file-extension">.mp4</span>
    </div>
    <button
        @click="generate"
        class="generate-btn"
        :disabled="(videos.length < 2 || !isValid) || generating"
    >
      <span v-if="generating">
        <i class="el-icon-loading"></i> 生成中...
      </span>
      <span v-else>
        生成拼接文件 ({{ videos.length }}/16)
      </span>
    </button>
  </div>
  <div v-if="concatVideoUrl" class="result-preview">
    <h3>剪辑结果预览</h3>
    <video
        ref="previewResultVideo"
        :src="videoPath+concatVideoUrl"
        controls
        class="preview-video"
    ></video>

    <div class="result-actions">
      <el-button
          type="primary"
          @click="downloadCutVideo"
          :loading="downloading"
      >
        <el-icon><Download /></el-icon>
        下载剪辑视频
      </el-button>
    </div>
  </div>
</template>

<script setup>
import {defineProps, defineEmits, ref, computed, onMounted} from 'vue';
import {ElMessage} from "element-plus";
import videoDataAPI from "../api/modules/videoData";
import {API_CONFIG} from "../api";
const videoPath =ref(API_CONFIG.IMAGE_URL);
const props = defineProps({
  videos: {
    type: Array,
    required: true
  }
});
const emit = defineEmits(['remove', 'generate']);
const outputFilename = ref('');
const concatVideoUrl = ref('');
const inputPathsUrl = ref('');
const videoUrl = ref(API_CONFIG.BASE_URL);
const downloading = ref(false);
const loading = ref(false);
const videoLoading = ref(false);
// 添加生成状态的loading变量
const generating = ref(false);

const formatDuration = (seconds) => {
  if (!seconds) return '00:00';
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};

const removeVideo = (index) => {
  emit('remove', index);
};
const generate = async () => {
  if (!isValid.value) {
    ElMessage.warning('请设置有效的文件名和剪辑范围');
    return;
  }

  // 开始生成前设置loading状态
  generating.value = true;
  try {
    const list = props.videos.map(item => item.absolutePath)
    const params = {
      inputPaths: list.join(','),
      outputPath: `${outputFilename.value}.mp4`,
      useReencode: true
    };
    const result = await videoDataAPI.concatVideoData(params);
    if (result?.code === 0) {
      ElMessage.success(`视频剪辑成功！`);
      concatVideoUrl.value = result.data
    } else {
      throw new Error(result?.msg || '获取数据失败');
    }
  } catch (error) {
    ElMessage.error(`生成失败: ${error.message}`);
  } finally {
    // 无论成功失败都关闭loading状态
    generating.value = false;
  }
};
// 下载剪辑视频
const downloadCutVideo = async () => {
  if (!concatVideoUrl.value) {
    ElMessage.warning('没有可下载的视频');
    return;
  }

  downloading.value = true;
  try {
    // 调用Electron API - 传递对象参数（与预加载脚本匹配）
    const result = await window.electronAPI.downloadVideo({
      url: videoPath.value + concatVideoUrl.value,          // 键名必须与主进程解构的键名一致
      defaultFilename: outputFilename.value  // 键名必须匹配
    });

    if (result.success) {
      ElMessage.success(`视频已保存至:\n${result.path}`);
    } else {
      ElMessage.warning(result.message || '下载已取消');
    }
  } catch (error) {
    console.error('下载失败:', error);
    ElMessage.error(`下载失败: ${error.message}`);
  } finally {
    downloading.value = false;
  }
};
const isValid = computed(() => {
  return outputFilename.value.trim() !== '' ;
});
// 暴露给父组件的方法
const reset = () => {
  // 重置逻辑
  concatVideoUrl.value = '';
  generating.value = false;
};
onMounted(() => {
  // 设置默认文件名
  outputFilename.value = '视频拼接';
});
defineExpose({
  reset
});
</script>

<style scoped>
.video-concat-editor {
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
  margin-top: 20px;
  background: #f9f9f9;
}

.selected-videos-list {
  margin: 20px 0;
  max-height: 300px;
  overflow-y: auto;
}

.concat-video-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  margin-bottom: 8px;
  background: white;
  border-radius: 4px;
  border-left: 4px solid #4CAF50;
}

.remove-btn {
  background: #ff5252;
  color: white;
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  cursor: pointer;
  font-weight: bold;
}

.generate-btn {
  display: block;
  width: 100%;
  padding: 12px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  margin-top: 20px;
  transition: background 0.2s;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.generate-btn:disabled {
  background: #a5d6a7;
  cursor: not-allowed;
}

.generate-btn:hover:not(:disabled) {
  background: #388E3C;
}

.filename-input {
  display: flex;
  align-items: center;
  margin: 20px 0;
}

.filename-input .el-input {
  flex: 1;
}

.file-extension {
  margin-left: 10px;
  color: #666;
}
.result-preview {
  margin-top: 30px;
  padding: 20px;
  border: 1px solid #e1e1e1;
  border-radius: 8px;
  background: #f8f8f8;
  transition: all 0.3s ease;
}

.result-preview h3 {
  margin-bottom: 15px;
  color: #333;
  text-align: center;
}

.preview-video {
  width: 100%;
  max-height: 400px;
  background: #000;
  border-radius: 4px;
  margin-bottom: 15px;
  display: block;
}

.result-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 15px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .preview-video {
    max-height: 300px;
  }

  .result-actions {
    flex-direction: column;
  }

  .result-actions button {
    width: 100%;
  }
}
</style>
